package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
)

func CmdEnableMultipartTransfer(repoPath string) error {
	repoAbsPath, err := filepath.Abs(repoPath)
	if err != nil {
		return fmt.Errorf("get repo abs path error: %w", err)
	}

	execPath, err := os.Executable()
	if err != nil {
		return fmt.Errorf("get exec path error: %w", err)
	}

	directionErr := setConfig(repoAbsPath, "lfs.customtransfer.gitee-multipart.direction", "upload")
	if directionErr != nil {
		return directionErr
	}

	execErr := setConfig(repoAbsPath, "lfs.customtransfer.gitee-multipart.path", execPath)
	if execErr != nil {
		return execErr
	}

	argsErr := setConfig(repoAbsPath, "lfs.customtransfer.gitee-multipart.args", "--lfs-multipart-upload")
	if argsErr != nil {
		return argsErr
	}

	// git config --global lfs.activitytimeout 7200
	timeoutErr := setConfig(repoAbsPath, "lfs.activitytimeout", "7200")
	if timeoutErr != nil {
		return timeoutErr
	}

	concurrentErr := setConfig(repoAbsPath, "lfs.concurrenttransfers", "3")
	if concurrentErr != nil {
		return concurrentErr
	}

	fmt.Println("enable multipart transfer success")

	return nil
}

func setConfig(repoAbsPath, key string, value string) error {
	cmd := exec.Command("git", "config", key, value)
	cmd.Dir = repoAbsPath
	err := cmd.Run()
	if err != nil {
		return fmt.Errorf("set %s error: %w", key, err)
	}

	return nil
}
